<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="迁出部门">
          <SelectOriganizationDangerGrant
            @change="(ids:string) => getSelectIds(ids,'original')"
            :isCheckStrictly="true"
            :isMultiple="false"
            :disabled="false"
            :data="dataObject('original')"
            :selectData="searchParam.originalDepartmentId"
          />
        </el-form-item>
        <el-form-item label="迁入部门">
          <SelectOriganizationDangerGrant
            @change="(ids:string) => getSelectIds(ids, 'target')"
            :isCheckStrictly="true"
            :isMultiple="false"
            :disabled="false"
            :data="dataObject('target')"
            :selectData="searchParam.targetDepartmentId"
          />
        </el-form-item>
        <el-form-item label="迁移时间">
          <el-date-picker
            v-model="searchParam.migrationTimeSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getmigrationTime"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchParam.migrationStatue"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="取消" :value="0" />
            <el-option label="新建" :value="1" />
            <el-option label="已确认" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备编码">
          <el-input
            v-model="searchParam.assetCode"
            placeholder="请输入设备编码"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input
            v-model="searchParam.assetName"
            placeholder="请输入设备名称"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()">
          <i-ep-plus />
          新增
        </el-button>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        :maxHeight="tableHeight"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          label="状态"
          prop="migrationStatue"
          min-width="80"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-tag v-if="scope.row.migrationStatue == 0" type="info"
              >取消</el-tag
            >
            <el-tag v-if="scope.row.migrationStatue == 1">新建</el-tag>
            <el-tag v-if="scope.row.migrationStatue == 2" type="success">
              已确认
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="设备编码"
          prop="assetCode"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="设备名称"
          prop="assetName"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="迁移原因"
          prop="migrationReason"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          label="迁移时间"
          prop="migrationTime"
          min-width="150"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="经办人"
          prop="handlerPersonName"
          min-width="80"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="迁出部门"
          prop="originalDepartmentName"
          min-width="120"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="迁出位置"
          prop="originalLocationName"
          min-width="120"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="迁入部门"
          prop="targetDepartmentName"
          min-width="120"
          show-overflow-tooltip
          align="center"
        />
        <!--        <el-table-column-->
        <!--          label="原使用人姓名"-->
        <!--          prop="originalUsingPersonName"-->
        <!--          min-width="100"-->
        <!--          show-overflow-tooltip-->
        <!--        />-->
        <!--        <el-table-column-->
        <!--          label="新使用人姓名"-->
        <!--          prop="targetUsingPersonName"-->
        <!--          min-width="100"-->
        <!--          show-overflow-tooltip-->
        <!--        />-->
        <el-table-column
          label="迁入位置"
          prop="targetLocationName"
          min-width="120"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="140" align="center">
          <template #default="scope">
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="查看"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialogdetail(scope.row)"
              >
                <i-ep-search />
              </el-button>
            </el-tooltip>
            <el-tooltip
              :hide-after="0"
              effect="light"
              content="编辑"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="openDialog(scope.row)"
              >
                <i-ep-edit />
              </el-button>
            </el-tooltip>

            <el-tooltip
              :hide-after="0"
              effect="light"
              content="删除"
              placement="top"
              v-if="
                [1, 0].includes(scope.row.migrationStatue) &&
                !authAllPerm(['eam:equ:eamassetmigrationapply:action'])
              "
            >
              <el-button
                type="primary"
                size="small"
                link
                @click="deleteItem(scope.row.id)"
              >
                <i-ep-delete />
              </el-button>
            </el-tooltip>
            <el-dropdown
              class="ml-[12px] align-middle!"
              v-if="authAllPerm(['eam:equ:eamassetmigrationapply:action'])"
            >
              <span
                class="el-dropdown-link text-[12px] c-[#409eff] cursor-pointer"
              >
                <i-ep-more class="text-[14px]!" />
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    @click="confirmData(scope.row)"
                    :disabled="scope.row.migrationStatue != 1"
                    >确认</el-dropdown-item
                  >
                  <el-dropdown-item
                    @click="closeItem(scope.row.id)"
                    :disabled="scope.row.migrationStatue != 1"
                    >取消</el-dropdown-item
                  >
                  <el-dropdown-item
                    :disabled="![1, 0].includes(scope.row.migrationStatue)"
                    @click="deleteItem(scope.row.id)"
                    >删除</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <eamassetmigrationapply-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :type="addDialog.type"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import {
  useTable,
  useDownload,
  useDictionary,
  useComputeTableHeight,
} from "@/utils/useTable";
import request from "@/utils/request";
import { authAllPerm } from "@/utils";

defineOptions({
  name: "EAMEAMASSETMIGRATIONAPPLY",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/eam/eamassetmigrationapply/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  assetCode: "",
  assetName: "",
  migrationTimeSearch: [],
  migrationTimeStart: "",
  migrationTimeEnd: "",
  migrationStatue: "",
  originalDepartmentId: "",
  targetDepartmentId: "",
};

const deleteParam = {
  api: "/eam/eamassetmigrationapply/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

// 定义tableHeight, 将计算注入dataCallBack回调中
const tableHeight = ref();
function dataCallBack(data: any) {
  setTimeout(() => {
    tableHeight.value = useComputeTableHeight();
  }, 100);
  return data;
}

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

const addDialog = reactive<DialogOption & { type: string }>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  type: "",
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/eamassetmigrationapply/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开资产迁移申请表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改资产迁移申请";
    getInfo(roleObj.id);
    addDialog.type = "edit";
  } else {
    addDialog.title = "新增资产迁移申请";
    addDialog.visible = true;
    addDialog.type = "add";
  }
  addDialog.readvisible = false;
}

/** 打开资产迁移申请表单弹窗 */
function confirmData(roleObj?: Object) {
  addDialog.title = "确认资产迁移申请";
  getInfo(roleObj.id);
  addDialog.type = "confirm";
  addDialog.readvisible = false;
}

/** 打开资产迁移申请表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "资产迁移申请详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
  addDialog.type = "detail";
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getmigrationTime(data: any) {
  if (data) {
    searchParam.value.migrationTimeStart = data[0];
    searchParam.value.migrationTimeEnd = data[1];
  } else {
    searchParam.value.migrationTimeStart = "";
    searchParam.value.migrationTimeEnd = "";
  }
}

async function closeItem(id: any) {
  ElMessageBox.confirm("确认取消已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/eam/eamassetmigrationapply/closeItem/${id}`,
      method: "post",
    });
    search();
  });
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/eam/eamassetmigrationapply/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}
const dataObject = (type) => {
  return {
    name: type === "original" ? "迁出部门" : "迁入部门",
    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};

/** 选择组织机构并赋值id  start **/
function getSelectIds(ids: [] | string, type: string) {
  if (type === "original") {
    searchParam.value.originalDepartmentId = ids;
  } else {
    searchParam.value.targetDepartmentId = ids;
  }
}
</script>
